package com.jerehedu.myapplication34.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.widget.GridView;

import com.jerehedu.myapplication34.R;
import com.jerehedu.myapplication34.util.DensityUtil;

/**
 * 重写gridView实现书架的功能
 * Created by yuzw on 12/31/14.
 */
public class MyGridView extends GridView {

    private Bitmap bg_left;
    private Bitmap bg_center;
    private Bitmap bg_right;

    public MyGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
        bg_left   = BitmapFactory.decodeResource(getResources(), R.drawable.bookshelf_layer_left);
        bg_center = BitmapFactory.decodeResource(getResources(), R.drawable.bookshelf_layer_center);
        bg_right  = BitmapFactory.decodeResource(getResources(), R.drawable.bookshelf_layer_right);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        int width = getWidth();
        int height = getHeight();

        int bg_left_width    = bg_left.getWidth();
        int bg_right_width   = bg_right.getWidth();
        int bg_center_width  = width - bg_left_width - bg_right_width;

        int backgroundHeight = DensityUtil.dip2px(getContext(),166);

        //int headerHeight = (int) (getResources().getDimension(R.dimen.bookshelf_header_height));

        Rect localRect1 = new Rect();
        Rect localRect2 = new Rect();
        Rect localRect3 = new Rect();
        int childCount = getChildCount();

        View child = childCount > 0 ? getChildAt(0) : null;

        int top = null != child ? child.getTop() : 0;
        for(int y=top;y<height;){
            localRect1.left   = 0;
            localRect1.top    = y;
            localRect1.right  = bg_left_width;
            localRect1.bottom = localRect1.top + backgroundHeight;
            //if( y == 0){
            //localRect1.bottom = localRect1.bottom + headerHeight;
            //}

            localRect2.left   = width - bg_right_width;
            localRect2.top    = localRect1.top;
            localRect2.right  = width;
            localRect2.bottom = localRect1.bottom;

            localRect3.left   = bg_left_width;
            localRect3.top    = localRect1.top;
            localRect3.right  = localRect3.left + bg_center_width;
            localRect3.bottom = localRect1.bottom;

            canvas.drawBitmap(bg_left, null, localRect1, null);
            canvas.drawBitmap(bg_right, null, localRect2, null);
            canvas.drawBitmap(bg_center, null, localRect3, null);
            y=localRect1.bottom;
        }

        super.dispatchDraw(canvas);

    }


}
